import { Button, DatePicker, Form, Space, Table } from "antd";
import type { ColumnsType } from "antd/es/table";
import dayjs from "dayjs";
import NP from "number-precision";
import { useEffect, useState } from "react";
import Filter from "~/components/ui/filter";
import ChannelRevenueCell from "~/components/ui/manage/channel/coin/channel-revenue-cell";
import { type IChartData } from "~/components/ui/manage/channel/coin/channel-revenue-chart-modal";
import Title from "~/components/ui/title";
import { useTableHeight } from "~/hooks/useTableHeight";
import type { IChannelMonthlyRevenue } from "~/types/manage/channel/coin";
import { amountToYuan, calculateTaxAmount, cn } from "~/utils/ui.util";

interface IFilter {
  year?: dayjs.Dayjs;
  name?: string;
}

/**
 * 收益看板
 * @returns
 */
export default function ExpenseBoard() {
  const [filterForm] = Form.useForm<IFilter>();
  const [recordForm] = Form.useForm<IChannelMonthlyRevenue>();
  const [monthList, setMonthList] = useState<string[]>([]);
  const [dataList, setDataList] = useState<IChannelMonthlyRevenue[]>([]);
  const tableHeight = useTableHeight(337);
  const [loading, setLoading] = useState(false);
  const watchYear = Form.useWatch("year", filterForm);

  const [editRecord, setEditRecord] = useState<IChannelMonthlyRevenue | null>(
    null,
  );
  const [editMonth, setEditMonth] = useState<string>();
  const [modalVisible, setModalVisible] = useState(false);

  const [chartModalVisible, setChartModalVisible] = useState(false);
  const [chartTitle, setChartTitle] = useState("");
  const [chartData, setChartData] = useState<IChartData[]>([]);

  const _handle = {
    editRevenue: (record: IChannelMonthlyRevenue, month: string) => {
      setEditRecord(record);
      setEditMonth(month);
      setModalVisible(true);
    },
    viewChart: (record?: IChannelMonthlyRevenue) => {
      setChartModalVisible(true);
      const dataArr: IChartData[] = [];
      if (record) {
        for (const key in record.revenues) {
          const value = record.revenues[key]?.amount;
          const invoiceAmount = amountToYuan(value);
          const taxValue = record.taxRate
            ? amountToYuan(calculateTaxAmount(value, record.taxRate))
            : 0;
          const afterTaxValue = NP.minus(invoiceAmount, taxValue);
          dataArr.push({
            month: key,
            value: invoiceAmount,
            type: "税前",
          });
          dataArr.push({
            month: key,
            value: afterTaxValue,
            type: "税后",
          });
          dataArr.push({
            month: key,
            value: taxValue,
            type: "扣税",
          });
        }
      } else {
        // 所有的
        monthList.map((itemMonth) => {
          let invoiceSum = 0;
          let taxSum = 0;
          let afterTaxValueSum = 0;
          for (const itemData of dataList) {
            const value = itemData.revenues[itemMonth]?.amount;
            const invoiceAmount = amountToYuan(value);
            const taxValue = itemData.taxRate
              ? amountToYuan(calculateTaxAmount(value, itemData.taxRate))
              : 0;
            const afterTaxValue = NP.minus(invoiceAmount, taxValue);
            invoiceSum = NP.plus(invoiceSum, invoiceAmount);
            taxSum = NP.plus(taxSum, taxValue);
            afterTaxValueSum = NP.plus(afterTaxValueSum, afterTaxValue || 0);
          }
          dataArr.push({
            month: itemMonth,
            value: invoiceSum,
            type: "税前",
          });
          dataArr.push({
            month: itemMonth,
            value: afterTaxValueSum,
            type: "税后",
          });
          dataArr.push({
            month: itemMonth,
            value: taxSum,
            type: "扣税",
          });
        });
      }
      setChartTitle(
        `${record?.name}-${watchYear?.year()}` ||
          `所有渠道总计-${watchYear?.year()}`,
      );
      setChartData(dataArr);
    },
  };

  const _ui: {
    tableSummary: (data: readonly IChannelMonthlyRevenue[]) => React.ReactNode;
    tableColumns: ColumnsType<IChannelMonthlyRevenue>;
  } = {
    tableSummary: (
      data: readonly IChannelMonthlyRevenue[],
    ): React.ReactNode => {
      return (
        <Table.Summary fixed>
          <Table.Summary.Row>
            <Table.Summary.Cell index={0}>总计</Table.Summary.Cell>
            {/* 计算总和 */}
            {monthList.map((itemMonth, index) => {
              let invoiceSum = 0;
              let taxSum = 0;
              let afterTaxValueSum = 0;
              for (const itemData of data) {
                const value = itemData.revenues[itemMonth]?.amount;
                const invoiceAmount = amountToYuan(value);
                const taxValue = itemData.taxRate
                  ? amountToYuan(calculateTaxAmount(value, itemData.taxRate))
                  : 0;
                const afterTaxValue = NP.minus(invoiceAmount, taxValue);
                invoiceSum = NP.plus(invoiceSum, invoiceAmount);
                taxSum = NP.plus(taxSum, taxValue);
                afterTaxValueSum = NP.plus(
                  afterTaxValueSum,
                  afterTaxValue || 0,
                );
              }
              return (
                <Table.Summary.Cell index={index + 1} key={index}>
                  <div
                    className={cn("text-xs", {
                      hidden: invoiceSum == 0,
                    })}
                  >
                    <div className="flex items-center gap-1">
                      <span className="text-gray-400">税前:</span>
                      <span className="font-bold text-[#34495e]">
                        {invoiceSum}
                      </span>
                    </div>
                    <div className="flex items-center gap-1">
                      <span className="text-gray-400">扣税:</span>
                      <span className="font-bold text-[#34495e]">{taxSum}</span>
                    </div>
                    <div className="flex items-center gap-1">
                      <span className="text-gray-400">税后:</span>
                      <span className="font-bold text-[#34495e]">
                        {afterTaxValueSum}
                      </span>
                    </div>
                  </div>
                </Table.Summary.Cell>
              );
            })}
            <Table.Summary.Cell index={13}>
              <div>
                <Space>
                  <Button
                    type="link"
                    size="small"
                    onClick={() => _handle.viewChart()}
                  >
                    查看统计图
                  </Button>
                </Space>
              </div>
            </Table.Summary.Cell>
          </Table.Summary.Row>
        </Table.Summary>
      );
    },
    tableColumns: [
      {
        title: "支出类型",
        dataIndex: "name",
        key: "name",
        fixed: "left",
        width: 140,
      },
      ...monthList.map((month, index) => {
        return {
          title: `${index + 1}月`,
          key: month,
          width: 100,
          render: (_: number, record: IChannelMonthlyRevenue) => {
            return (
              <ChannelRevenueCell
                record={record}
                month={month}
                editRevenue={_handle.editRevenue}
              />
            );
          },
        };
      }),
      {
        title: "操作",
        width: 120,
        fixed: "right",
        render: (record: IChannelMonthlyRevenue) => {
          return (
            <Space>
              <Button
                type="link"
                size="small"
                onClick={() => _handle.viewChart(record)}
              >
                查看统计图
              </Button>
            </Space>
          );
        },
      },
    ],
  };

  const _fetch = {
    monthlyRevenue: async (params: {
      year: dayjs.Dayjs | string;
      name: string;
    }) => {
      setLoading(true);
      try {
        const tempYear =
          typeof params.year === "string"
            ? params.year
            : params.year.format("YYYY");
        // const resp = await apiChannelMonthlyRevenue({
        //   ...params,
        //   year: tempYear,
        // });
        setDataList([]);
      } catch (error) {
      } finally {
        setLoading(false);
      }
    },
  };

  useEffect(() => {}, []);

  useEffect(() => {
    if (watchYear) {
      setMonthList(
        new Array(12)
          .fill(0)
          .map((item, index) => dayjs(watchYear).month(index).format("YYYYMM")),
      );
      _fetch.monthlyRevenue(filterForm.getFieldsValue(true));
    }
  }, [watchYear]);

  return (
    <>
      <Title title="月支出看板" />
      <Filter
        form={filterForm}
        initialValues={{
          year: dayjs(dayjs().format("YYYY")),
        }}
      >
        <Form.Item label={"年份"} name={"year"}>
          <DatePicker picker="year" />
        </Form.Item>
      </Filter>
      <Form form={recordForm} component={false}>
        <Table
          size="small"
          loading={loading}
          bordered
          pagination={false}
          className={"rp-[.ant-form-item]:!mb-0"}
          scroll={{
            y: tableHeight,
            x: "max-content",
          }}
          rowKey={(record) => record.id}
          summary={_ui.tableSummary}
          columns={_ui.tableColumns}
          dataSource={dataList}
          locale={{
            emptyText: "暂无数据",
          }}
        />
      </Form>
      {/* <ChannelRevenueChartModal
        title={chartTitle}
        visible={chartModalVisible}
        data={chartData}
        year={watchYear?.format("YYYY")}
        onCancel={() => {
          setChartModalVisible(false);
          setChartData([]);
        }}
      /> */}
    </>
  );
}
